package com.crm.system.service.impl.customerManager;

import com.beust.jcommander.internal.Lists;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.customerManager.SingleProductCustomer;
import com.crm.model.entity.customerManager.SingleProductCustomerContact;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.customerManager.SingleProductCustomerContactQO;
import com.crm.model.qo.customerManager.SingleProductCustomerQO;
import com.crm.model.vo.cluePoolManager.ClueFollowVO;
import com.crm.model.vo.cluePoolManager.ClueVisitRecordVO;
import com.crm.model.vo.customerManager.SingleProductCustomerVO;
import com.crm.service.cluePoolManager.ClueFollowDbService;
import com.crm.service.cluePoolManager.ClueVisitRecordDbService;
import com.crm.service.customerManager.SingleProductCustomerContactDbService;
import com.crm.service.customerManager.SingleProductCustomerDbService;
import com.crm.system.service.customerManager.SingleProductCustomerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @ Author ：pym
 * @ Date   ：2021/4/29 15:20
 */
@Service
public class SingleProductCustomerServiceImpl implements SingleProductCustomerService {
    @Autowired
    private SingleProductCustomerDbService singleProductCustomerDbService;

    @Autowired
    private ClueFollowDbService clueFollowDbService;

    @Autowired
    private ClueVisitRecordDbService clueVisitRecordDbService;

    @Autowired
    private SingleProductCustomerContactDbService singleProductCustomerContactDbService;

    /**
     * 客户管理-单品客户
     * @Author pym
     * @Date  2021/4/29 15:21
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param singleProductCustomerQO -查询条件
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @return {@link {com.crm.common.model.DhPageInfo<com.crm.model.vo.customerManager.SingleProductCustomerVO>}}
     */
    @Override
    public DhPageInfo<SingleProductCustomerVO> selectSingleProductCustomerList(Integer pageIndex, Integer pageSize, SingleProductCustomerQO singleProductCustomerQO, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        String dateType = singleProductCustomerQO.getDateType();
        //日期类型(全部/本周/本月/本年度)
        Integer dateUnit = getDateUnit(dateType);
        //排序字符串拼接
        String order = getOrder(sortName, sortOrder);
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        /*List<SingleProductCustomerVO> singleProductCustomerVOList = new ArrayList<SingleProductCustomerVO>();
        if (CommonUtils.isAdmin(userAccount.getUserId())) {//超级管理员
            singleProductCustomerVOList = singleProductCustomerDbService.selectAllSingleProductCustomerList(singleProductCustomerQO, dateUnit, order);
        } else {//普通管理员
            String accountId = userAccount.getAccountId();//获取登录人ID
            singleProductCustomerVOList = singleProductCustomerDbService.selectNormalSingleProductCustomerList(singleProductCustomerQO, dateUnit, order, accountId);
        }*/
        String accountId = userAccount.getAccountId();//获取登录人ID
        List<SingleProductCustomerVO> singleProductCustomerVOList
                = singleProductCustomerDbService.selectNormalSingleProductCustomerList(singleProductCustomerQO, dateUnit, order, accountId);
        PageInfo<SingleProductCustomerVO> pageInfo = new PageInfo<SingleProductCustomerVO>(singleProductCustomerVOList);
        return new DhPageInfo<SingleProductCustomerVO>(pageInfo, singleProductCustomerVOList);
    }

    /**
     * 日期类型(全部/本周/本月/本年度)
     * @Author pym
     * @Date  2021/4/29 16:38
     * @param dateType -(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年)
     * @return {@link {java.lang.Integer}}
     */
    private Integer getDateUnit(String dateType) {
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(dateType)) {
                //本年
                dateUnit = 3;
            }
            if ("lastMonth".equals(dateType)) {
                //上月
                dateUnit = 4;
            }
        }
        return dateUnit;
    }

    /**
     * 排序字符串拼接
     * @Author pym
     * @Date  2021/4/29 16:38
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @return {@link {java.lang.String}}
     */
    private String getOrder(String sortName, String sortOrder) {
        String order = "";
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch(sortName){
                case "customerName":
                { //订单编号
                    order = getOrder(order, sortOrder, "customer_name");
                }
                break;
                case "createTm":
                { //订单状态
                    order = getOrder(order, sortOrder, "create_tm");
                }
                break;
                default:
                    break;
            }
        }
        if (!order.contains("create_tm")) {
            order = getOrder(order, "DESC", "create_tm");
        }
        return order;
    }

    /**
     * 排序字符串拼接
     * @Author pym
     * @Date  2021/4/29 16:41
     * @param order -排序字符串
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @return {@link {java.lang.String}}
     */
    private String getOrder(String order, String sortOrder, String sortName) {
        if (StringUtils.isBlank(order)) {
            order += sortName +" "+ sortOrder;
        } else {
            order += ","+sortName +" " + sortOrder;
        }
        return order;
    }

    /**
     * 新增单品客户
     * @Author pym
     * @Date  2021/4/30 11:49
     * @param customerId 客户ID
     * @return {@link {java.lang.String}}
     */
    @Override
    public String addSingleProductCustomer(String customerId) {
        if (StringUtils.isNotBlank(customerId)) {
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
            String accountId = userAccount.getAccountId();
            Boolean singleProductCustomerRepeat = singleProductCustomerDbService.isSingleProductCustomerRepeat(customerId, accountId);
            if (!singleProductCustomerRepeat) {
                SingleProductCustomer singleProductCustomer = getSingleProductCustomer(customerId, accountId);
                singleProductCustomerDbService.insertSingleProductCustomer(singleProductCustomer);
                //保存成功
                return "C00000";
            } else {
                //单品客户已存在
                return "C00001";
            }
        } else {
            //客户ID为空
            return "C00002";
        }
    }

    /**
     * 获取单品客户
     * @Author pym
     * @Date  2021/4/30 13:28
     * @param customerId 开会ID
     * @return {@link {com.crm.model.entity.customerManager.SingleProductCustomer}}
     */
    private SingleProductCustomer getSingleProductCustomer(String customerId, String accountId) {
        SingleProductCustomer singleProductCustomer = new SingleProductCustomer();
        singleProductCustomer.setSingleProductCustomerId(CommonUtils.getGUID());
        singleProductCustomer.setCustomerId(customerId);
        singleProductCustomer.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        singleProductCustomer.setCreatePeopleId(accountId);
        singleProductCustomer.setCreateTm(new Date());
        singleProductCustomer.setUpdatePeopleId(accountId);
        singleProductCustomer.setUpdateTm(new Date());
        return singleProductCustomer;
    }

    /**
     * 单品客户跟进记录
     * @Author pym
     * @Date  2021/5/12 10:59
     * @param pageIndex 页码
     * @param pageSize 分页大小
     * @param sortName 排序列名字
     * @param sortOrder 排序规则(asc/desc)
     * @param singleProductCustomerId 单品客户ID
     * @return {@link {com.crm.common.model.DhPageInfo<com.crm.model.vo.cluePoolManager.ClueFollowVO>}}
     */
    @Override
    public DhPageInfo<ClueFollowVO> selectClueFollowList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String singleProductCustomerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<ClueFollowVO> clueFollowVOList = clueFollowDbService.selectClueFollowListByCustomerId(order.toString(),singleProductCustomerId,accountId);
        PageInfo<ClueFollowVO> pageInfo = new PageInfo<ClueFollowVO>(clueFollowVOList);
        return new DhPageInfo<ClueFollowVO>(pageInfo, clueFollowVOList);
    }


    /**
     * @Description: 根据客户ID获取单品客户跟进记录
     * @Param: [singleProductCustomerId]
     * @Return: java.util.List<com.crm.model.vo.cluePoolManager.ClueFollowVO>
     * @Author: lixq-f
     * @Date: 2021/5/24
     **/
    @Override
    public List<ClueFollowVO> selectSingleFollowsByCustomerId(String singleProductCustomerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        List<ClueFollowVO> clueFollowVOList =
                clueFollowDbService.selectClueFollowListByCustomerId("create_tm",singleProductCustomerId,accountId);

        if (CollectionUtils.isEmpty(clueFollowVOList))
            clueFollowVOList = Lists.newArrayList();

        return clueFollowVOList;
    }


    /**
     * 单品客户拜访记录
     * @Author pym
     * @Date  2021/5/12 16:54
     * @param pageIndex 页码
     * @param pageSize 分页大小
     * @param sortName 排序列名字
     * @param sortOrder 排序规则(asc/desc)
     * @param singleProductCustomerId 单品客户ID
     * @return {@link {com.crm.common.model.DhPageInfo<com.crm.model.vo.cluePoolManager.ClueVisitRecordVO>}}
     */
    @Override
    public DhPageInfo<ClueVisitRecordVO> selectClueVisitRecordList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String singleProductCustomerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<ClueVisitRecordVO> clueVisitRecordVOList = clueVisitRecordDbService.selectSingleProductCustomerClueVisitRecordList(singleProductCustomerId, order.toString(), accountId);
        PageInfo<ClueVisitRecordVO> pageInfo = new PageInfo<ClueVisitRecordVO>(clueVisitRecordVOList);
        return new DhPageInfo<ClueVisitRecordVO>(pageInfo, clueVisitRecordVOList);
    }

    /**
     * 单品客户联系人
     * @Author pym
     * @Date  2021/5/12 18:28
     * @param pageIndex 页码
     * @param pageSize 分页大小
     * @param sortName 排序列名字
     * @param sortOrder 排序规则(asc/desc)
     * @param singleProductCustomerId 单品客户主键ID
     * @return {@link {com.crm.common.model.DhPageInfo<com.crm.model.entity.customerManager.SingleProductCustomerContact>}}
     */
    @Override
    public DhPageInfo<SingleProductCustomerContact> selectSingleProductCustomerContactList(Integer pageIndex, Integer pageSize,
                                                                                           String sortName, String sortOrder, String singleProductCustomerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<SingleProductCustomerContact> singleProductCustomerContactList = singleProductCustomerContactDbService.selectSingleProductCustomerContactList(singleProductCustomerId,accountId);
        PageInfo<SingleProductCustomerContact> pageInfo = new PageInfo<SingleProductCustomerContact>(singleProductCustomerContactList);
        return new DhPageInfo<SingleProductCustomerContact>(pageInfo, singleProductCustomerContactList);
    }


    /**
     * @Description: 根据客户ID获取单品客户联系人
     * @Param: [singleProductCustomerId]
     * @Return: java.util.List<com.crm.model.entity.customerManager.SingleProductCustomerContact>
     * @Author: lixq-f
     * @Date: 2021/5/24
     **/
    @Override
    public List<SingleProductCustomerContact> singleCustomerContactByCustomerId(String singleProductCustomerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        List<SingleProductCustomerContact> singleProductCustomerContactList =
                singleProductCustomerContactDbService.selectSingleProductCustomerContactList(singleProductCustomerId,accountId);

        if (CollectionUtils.isEmpty(singleProductCustomerContactList))
            singleProductCustomerContactList =  Lists.newArrayList();

        return singleProductCustomerContactList;
    }


    /**
     * 新增单品客户联系人
     * @Author pym
     * @Date  2021/5/13 10:35
     * @param singleProductCustomerContactQO 单品客户联系人参数
     * @return {@link {java.lang.Boolean}}
     */
    @Override
    public String addSingleProductCustomerContact(SingleProductCustomerContactQO singleProductCustomerContactQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        //String singleProductCustomerId = singleProductCustomerContactQO.getSingleProductCustomerId();
        String contactInformation = singleProductCustomerContactQO.getContactInformation();
        //单品客户联系方式针对所有账号唯一
        Boolean contactInformationRepeated = singleProductCustomerContactDbService.isContactInformationRepeated(contactInformation);
        if (contactInformationRepeated) {
            return "S000002";//单品客户联系方式重复
        }
        SingleProductCustomerContact singleProductCustomerContact = getSingleProductCustomerContact(singleProductCustomerContactQO, accountId);
        Boolean result = singleProductCustomerContactDbService.addSingleProductCustomerContact(singleProductCustomerContact);
        if (!result) {
            return "S000001";//保存失败
        }
        return "S000000";//保存成功
    }

    /**
     * 单品客户联系人
     * @Author pym
     * @Date  2021/5/13 11:04
     * @param singleProductCustomerContactQO 单品客户联系人参数
     * @param accountId 账号Id
     * @return {@link {com.crm.model.entity.customerManager.SingleProductCustomerContact}}
     */
    private SingleProductCustomerContact getSingleProductCustomerContact(SingleProductCustomerContactQO singleProductCustomerContactQO, String accountId) {
        SingleProductCustomerContact singleProductCustomerContact = new SingleProductCustomerContact();
        singleProductCustomerContact.setSingleProductCustomerContactId(CommonUtils.getGUID());
        singleProductCustomerContact.setContactName(singleProductCustomerContactQO.getContactName());
        singleProductCustomerContact.setContactInformation(singleProductCustomerContactQO.getContactInformation());
        singleProductCustomerContact.setContactPosition(singleProductCustomerContactQO.getContactPosition());
        singleProductCustomerContact.setIsSeniorExecutive(singleProductCustomerContactQO.getIsSeniorExecutive());
        singleProductCustomerContact.setOnTheJobSituation(singleProductCustomerContactQO.getOnTheJobSituation());
        singleProductCustomerContact.setWeChat(singleProductCustomerContactQO.getWeChat());
        singleProductCustomerContact.setMailBox(singleProductCustomerContactQO.getMailBox());
        singleProductCustomerContact.setSingleProductCustomerId(singleProductCustomerContactQO.getSingleProductCustomerId());
        singleProductCustomerContact.setCreatePeopleId(accountId);
        singleProductCustomerContact.setCreateTm(new Date());
        singleProductCustomerContact.setUpdatePeopleId(accountId);
        singleProductCustomerContact.setUpdateTm(new Date());
        singleProductCustomerContact.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        return singleProductCustomerContact;
    }

    /**
     * 单品客户线上跟进联系人
     * @Author pym
     * @Date  2021/5/13 14:30
     * @param singleProductCustomerId 单品客户主键ID
     * @return {@link {java.util.List<com.crm.model.entity.customerManager.SingleProductCustomerContact>}}
     */
    @Override
    public List<SingleProductCustomerContact> selectSingleProductCustomerContacts(String singleProductCustomerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        return singleProductCustomerContactDbService.selectSingleProductCustomerContactById(singleProductCustomerId, userAccount.getAccountId());
    }

    /**
     * 单品客户线上跟进判断联系人是否存在
     * @Author pym
     * @Date  2021/6/16 14:08
     * @param singleProductCustomerId 单品客户Id
     * @param contactInformation 联系方式
     * @param accountId 账号Id
     * @return {@link {com.crm.model.entity.customerManager.SingleProductCustomerContact}}
     */
    public SingleProductCustomerContact getSingleProductCustomerContactById(String singleProductCustomerId, String contactInformation, String accountId) {
        return singleProductCustomerContactDbService.getSingleProductCustomerContactById(singleProductCustomerId, contactInformation, accountId);
    }

    /**
     * 删除单品客户
     * @Author pym
     * @Date  2021/7/15 10:06
     * @param singleProductCustomerId 单品客户Id
     * @return {@link {java.lang.Boolean}}
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void deleteSingleProductCustomer(String singleProductCustomerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        SingleProductCustomer singleProductCustomer = new SingleProductCustomer();
        singleProductCustomer.setSingleProductCustomerId(singleProductCustomerId);
        singleProductCustomer.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
        singleProductCustomer.setUpdatePeopleId(userAccount.getAccountId());
        singleProductCustomer.setUpdateTm(new Date());
        //删除单品客户
        singleProductCustomerDbService.updateSingleProductCustomerById(singleProductCustomer);
        //查询单品客户下联系人Ids
        List<String> idList = singleProductCustomerContactDbService.selectSingleProductCustomerContactIdList(singleProductCustomerId);
        if (idList != null && idList.size() > 0) {
            //批量删除单品客户下联系人
            singleProductCustomerContactDbService.batchDelSingleProductCustomerContactByIds(idList);
        }
    }

}
